import os
import time
import subprocess

VIRTUAL_IP = "192.168.0.100"  # Replace with your VIP
INTERFACE = "eth0"            # Replace with your network interface
HEALTH_CHECK_FILE = "/tmp/host_health_check"  # A file to indicate host health

# Assign VIP to the host
def assign_vip():
    try:
        subprocess.run(f"sudo ip addr add {VIRTUAL_IP}/24 dev {INTERFACE}", shell=True, check=True)
        print(f"VIP {VIRTUAL_IP} assigned to {INTERFACE}")
    except subprocess.CalledProcessError as e:
        print(f"Error assigning VIP: {e}")

# Remove VIP from the host
def remove_vip():
    try:
        subprocess.run(f"sudo ip addr del {VIRTUAL_IP}/24 dev {INTERFACE}", shell=True, check=True)
        print(f"VIP {VIRTUAL_IP} removed from {INTERFACE}")
    except subprocess.CalledProcessError as e:
        print(f"Error removing VIP: {e}")

# Health check logic
def is_healthy():
    return os.path.exists(HEALTH_CHECK_FILE)

# Host monitoring logic
def host_logic():
    vip_assigned = False
    while True:
        if is_healthy():
            print("Host is healthy.")
            if not vip_assigned:
                assign_vip()
                vip_assigned = True
        else:
            print("Host is unhealthy.")
            if vip_assigned:
                remove_vip()
                vip_assigned = False
        time.sleep(5)

if __name__ == "__main__":
    host_logic()
